#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author：TanDabao
# CreateTime：2021/10/22 16:52

import requests
from lxml import etree

def login():
    # cacti登录函数

    proxies = {"http": None, "https": None}
    init_url = 'http://103.45.102.58:8055/index.php'
    session = requests.Session()

    # 获取登录页面元素
    response = session.get(init_url, proxies=proxies)
    response.encoding = 'utf-8'
    init_html = response.text

    # 获取动态参数
    tree = etree.HTML(init_html)
    name = tree.xpath('//body/form/input[1]/@name')[0]
    value = tree.xpath('//body/form/input[1]/@value')[0]

    headers = {
        'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Mobile Safari/537.36',
        'Host': '103.45.102.58:8055',
        'Origin': 'http://103.45.102.58:8055',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Referer': 'http://103.45.102.58:8055/index.php',
    }

    data = {
        name: value,
        'action': 'login',
        'login_username': 'admin',
        'login_password': 'xxxxxx'
    }


    # 获取cookies
    for key, value in response.cookies.items():
        print(key, value)
        cookie = key + '=' + value
    cookie_dict = {'Cookie': cookie}
    # 关键点
    session.cookies.update(cookie_dict)

    # 登录
    res = session.post(url=init_url, proxies=proxies, headers=headers, data=data)
    res.encoding = 'utf-8'
    login_html = res.text
    #print(login_html)

    tuxing_url = 'http://103.45.102.58:8055/graph_view.php'
    tuxing = session.get(url=tuxing_url)
    tuxing.encoding = 'utf-8'
    view_html = tuxing.text

    print(view_html)


